<?php

namespace App\Http\Controllers;

use App\Models\Sites;
use Illuminate\Http\Request;
use App\Models\Startend;
use App\Models\Category;

class StartendController extends Controller
{
    //
    public function create($site = null)
    {
        if ($site) {
            $site = Sites::where('id', $site)->first();
            $startends = $site->startends()->paginate(5);
        } else {
            $startends = Startend::paginate(5);
        }

        $sites = Sites::all();
        return view('startend.index', compact('startends', 'sites'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'sites_id' => 'required',
            'value' => 'required',
            'type' => 'required'
        ]);

        $result = Startend::create([
            'sites_id' => $request->sites_id,
            'value' => $request->value,
            'type' => $request->type,
        ]);
        if ($result) {
            session()->flash('success', '添加成功');
        } else {
            session()->flash('error', '添加失败');
        }
        return redirect()->route('startend.create');
    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'sites_id' => 'required',
            'value' => 'required',
            'type' => 'required'
        ]);
        $startend = Startend::find($id);
        if (!$startend) {
            session()->flash('error', '404');
        }
        $startend->sites_id = $request->sites_id;
        $startend->value = $request->value;
        $startend->type = $request->type;
        $result = $startend->save();
        if ($result) {
            session()->flash('success', '修改成功');
        } else {
            session()->flash('error', '修改失败');
        }
        return redirect()->route('startend.create');
    }

    public function destroy($id)
    {
        $tag = Startend::findOrFail($id);
        $tag->delete();
        return redirect()->route('startend.create');
    }
}
